#!/usr/bin/env python3
# coding:utf-8
import time
import threading
import sched


class Async_Timer:
    def __init__(self):
        self.aync_sched = sched.scheduler(time.time, time.sleep)
        self.thread_timer = None
        self.sched_list = {}

    def add_timer(self, id, delay, priority, action, args: tuple):
        event = self.aync_sched.enter(delay, priority, action, args)
        self.sched_list["id"] = event

    def del_timer(self,id):
        """
        已运行的sched无法删除
        """
        if id in self.sched_list:
            event = self.sched_list[id]
            self.aync_sched.cancel(event)
            self.sched_list.pop(id)

    def __async_run(self):
        self.aync_sched.run()

    def async_run(self):
        # 独立线程执行, 实现异步定时器
        self.thread_timer = threading.Timer(1, self.__async_run)
        self.thread_timer.start()

    def is_running(self):
        return self.aync_sched.empty()

    def wait_run_finish(self, poll_period=1):
        while self.aync_sched.empty() == False:
            print("wait run finish")
            time.sleep(poll_period)


def test_fun(buf):
    print("test_fun: ", buf)


async_timer = Async_Timer()
async_timer.add_timer("test1", 5, 1, test_fun, ("aaa",))
async_timer.add_timer("test2", 10, 1, test_fun, ("bbb",))
async_timer.async_run()
print(async_timer.is_running())
async_timer.del_timer("test2")
async_timer.wait_run_finish()
print(async_timer.is_running())
print("end")
